/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.org.ccb.ccbadm.auth;

//import br.edu.ifro.coreedu.entities.Permissao;
//import br.edu.ifro.coreedu.entities.Usuario;
import br.org.ccb.ccbadm.model.Usuario;
import br.org.ccb.ccbadm.connection.PersistenceFactory;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Cache;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

/**
 *
 * @author alan
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        
        Usuario usuario;
        
        /* Zerando o Cache*/
        Cache cache = PersistenceFactory.getPersistenceTransaction().getEntityManager().getEntityManagerFactory().getCache();
        cache.evict(Usuario.class);
        /*  +++++++++++++ */
        //PersistenceFactory.getPersistenceTransaction().getEntityManager().clear();

        Query query = PersistenceFactory.getPersistenceTransaction().getEntityManager().createNamedQuery("Usuario.authenticate");
        query.setParameter("senha", CriptografiaUtil.obterInstancia().criptografarComMD5(password));
        query.setParameter("login", name);

        try {
            usuario = (Usuario) query.getSingleResult();
            List<GrantedAuthority> grantedAuths;
            grantedAuths = new ArrayList();

//implementar Permissao
/*            for (Permissao perm: usuario.getPermissaoList()) {
                grantedAuths.add(new SimpleGrantedAuthority(perm.getGrupo().getNome()));
            }
*/            
            Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
            

            
            return auth;
            
        }
        catch (NoResultException nre) {
            throw new AuthenticationCredentialsNotFoundException("Usuário e senha inválidos");
        }

        
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
    
}
